<template>
  <div class="address-form-page">
    <div class="container">
      <div class="page-header">
        <el-button @click="handleBack" :icon="ArrowLeft" circle />
        <h1>{{ isEdit ? '编辑地址' : '添加地址' }}</h1>
        <div class="placeholder"></div>
      </div>

      <el-card class="form-card">
        <el-form
          ref="formRef"
          :model="form"
          :rules="rules"
          label-width="100px"
          @submit.prevent="handleSubmit"
        >
          <el-form-item label="地址标签" prop="label">
            <div class="label-section">
              <div class="preset-labels">
                <el-tag
                  v-for="presetLabel in presetLabels"
                  :key="presetLabel"
                  :type="form.label === presetLabel ? 'primary' : 'info'"
                  class="label-tag"
                  @click="selectLabel(presetLabel)"
                >
                  {{ presetLabel }}
                </el-tag>
              </div>
              <el-input
                v-model="form.label"
                placeholder="或自定义标签"
                maxlength="10"
                show-word-limit
              />
            </div>
          </el-form-item>

          <el-form-item label="联系人" prop="contactName">
            <el-input
              v-model="form.contactName"
              placeholder="请输入联系人姓名"
              maxlength="20"
            />
          </el-form-item>

          <el-form-item label="联系电话" prop="contactPhone">
            <el-input
              v-model="form.contactPhone"
              placeholder="请输入联系电话"
              maxlength="11"
            />
          </el-form-item>

          <el-form-item label="所在地区" prop="region">
            <el-cascader
              v-model="form.region"
              :options="regionOptions"
              placeholder="请选择省市区"
              :props="cascaderProps"
              clearable
              filterable
              style="width: 100%"
              @change="handleRegionChange"
            />
          </el-form-item>

          <el-form-item label="详细地址" prop="detailAddress">
            <el-input
              v-model="form.detailAddress"
              type="textarea"
              :rows="3"
              placeholder="请输入详细地址（街道、楼栋、门牌号等）"
              maxlength="100"
              show-word-limit
            />
            <div class="location-helper">
              <el-button
                size="small"
                type="primary"
                link
                @click="getCurrentLocation"
                :loading="locationLoading"
              >
                <el-icon><Location /></el-icon>
                获取当前位置
              </el-button>
            </div>
          </el-form-item>

          <el-form-item label="地址标签">
            <div class="address-tags">
              <el-checkbox-group v-model="form.tags">
                <el-checkbox label="家">家</el-checkbox>
                <el-checkbox label="公司">公司</el-checkbox>
                <el-checkbox label="学校">学校</el-checkbox>
                <el-checkbox label="其他">其他</el-checkbox>
              </el-checkbox-group>
            </div>
          </el-form-item>

          <el-form-item>
            <el-checkbox v-model="form.isDefault">设为默认地址</el-checkbox>
          </el-form-item>

          <el-form-item class="form-actions">
            <el-button @click="handleBack">取消</el-button>
            <el-button
              type="primary"
              @click="handleSubmit"
              :loading="submitting"
            >
              {{ isEdit ? '保存' : '添加' }}
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>

      <!-- 位置选择对话框 -->
      <el-dialog
        v-model="showLocationDialog"
        title="选择位置"
        width="600px"
        :before-close="handleCloseLocationDialog"
      >
        <div class="location-content">
          <div class="search-section">
            <el-input
              v-model="locationSearch"
              placeholder="搜索地址..."
              clearable
              @keyup.enter="searchLocation"
            >
              <template #append>
                <el-button @click="searchLocation" :loading="searchLoading">
                  搜索
                </el-button>
              </template>
            </el-input>
          </div>
          
          <div class="map-container">
            <div id="location-map" style="width: 100%; height: 300px;"></div>
          </div>
          
          <div class="location-results" v-if="searchResults.length">
            <h4>搜索结果</h4>
            <div
              v-for="result in searchResults"
              :key="result.id"
              class="result-item"
              @click="selectLocation(result)"
            >
              <h5>{{ result.title }}</h5>
              <p>{{ result.address }}</p>
            </div>
          </div>
        </div>
        
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="showLocationDialog = false">取消</el-button>
            <el-button type="primary" @click="confirmLocation">确定</el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ArrowLeft, Location } from '@element-plus/icons-vue'
import { addressApi } from '@/services/api'

const route = useRoute()
const router = useRouter()

// 数据定义
const formRef = ref()
const submitting = ref(false)
const locationLoading = ref(false)
const showLocationDialog = ref(false)
const searchLoading = ref(false)
const locationSearch = ref('')
const searchResults = ref([])

const form = reactive({
  label: '',
  contactName: '',
  contactPhone: '',
  region: [],
  detailAddress: '',
  tags: [],
  isDefault: false
})

const presetLabels = ['家', '公司', '学校', '小区', '写字楼', '其他']

// 地区选择配置
const cascaderProps = {
  value: 'code',
  label: 'name',
  children: 'children',
  emitPath: false
}

// 模拟地区数据（实际项目中应该从API获取）
const regionOptions = ref([
  {
    code: '110000',
    name: '北京市',
    children: [
      {
        code: '110100',
        name: '市辖区',
        children: [
          { code: '110101', name: '东城区' },
          { code: '110102', name: '西城区' },
          { code: '110105', name: '朝阳区' },
          { code: '110106', name: '丰台区' },
          { code: '110107', name: '石景山区' },
          { code: '110108', name: '海淀区' },
          { code: '110109', name: '门头沟区' },
          { code: '110111', name: '房山区' },
          { code: '110112', name: '通州区' },
          { code: '110113', name: '顺义区' }
        ]
      }
    ]
  },
  {
    code: '310000',
    name: '上海市',
    children: [
      {
        code: '310100',
        name: '市辖区',
        children: [
          { code: '310101', name: '黄浦区' },
          { code: '310104', name: '徐汇区' },
          { code: '310105', name: '长宁区' },
          { code: '310106', name: '静安区' },
          { code: '310107', name: '普陀区' },
          { code: '310109', name: '虹口区' },
          { code: '310110', name: '杨浦区' },
          { code: '310112', name: '闵行区' },
          { code: '310113', name: '宝山区' },
          { code: '310114', name: '嘉定区' }
        ]
      }
    ]
  }
])

// 表单验证规则
const rules = {
  label: [
    { required: true, message: '请输入地址标签', trigger: 'blur' }
  ],
  contactName: [
    { required: true, message: '请输入联系人姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '姓名长度在2到20个字符', trigger: 'blur' }
  ],
  contactPhone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  region: [
    { required: true, message: '请选择所在地区', trigger: 'change' }
  ],
  detailAddress: [
    { required: true, message: '请输入详细地址', trigger: 'blur' },
    { min: 5, max: 100, message: '详细地址长度在5到100个字符', trigger: 'blur' }
  ]
}

// 计算属性
const isEdit = computed(() => route.name === 'EditAddress')

// 生命周期
onMounted(() => {
  if (isEdit.value) {
    fetchAddressDetail()
  }
})

// 方法定义
const fetchAddressDetail = async () => {
  try {
    const response = await addressApi.getAddressDetail(route.params.id)
    const address = response.data
    
    Object.assign(form, {
      label: address.label,
      contactName: address.contactName,
      contactPhone: address.contactPhone,
      region: address.region,
      detailAddress: address.detailAddress,
      tags: address.tags || [],
      isDefault: address.isDefault
    })
  } catch (error) {
    console.error('获取地址详情失败:', error)
    ElMessage.error('获取地址详情失败')
  }
}

const selectLabel = (label) => {
  form.label = label
}

const handleRegionChange = (value) => {
  console.log('选中地区:', value)
}

const getCurrentLocation = async () => {
  locationLoading.value = true
  
  try {
    if (!navigator.geolocation) {
      throw new Error('浏览器不支持定位功能')
    }
    
    const position = await new Promise((resolve, reject) => {
      navigator.geolocation.getCurrentPosition(resolve, reject, {
        enableHighAccuracy: true,
        timeout: 10000,
        maximumAge: 60000
      })
    })
    
    const { latitude, longitude } = position.coords
    
    // 这里应该调用地图API进行逆地理编码
    // 模拟返回地址信息
    const address = await reverseGeocode(latitude, longitude)
    form.detailAddress = address
    
    ElMessage.success('位置获取成功')
  } catch (error) {
    console.error('获取位置失败:', error)
    ElMessage.error('获取位置失败，请手动输入地址')
  } finally {
    locationLoading.value = false
  }
}

const reverseGeocode = async (lat, lng) => {
  // 模拟逆地理编码
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve('中关村大街1号院')
    }, 1000)
  })
}

const searchLocation = async () => {
  if (!locationSearch.value.trim()) {
    ElMessage.warning('请输入搜索关键词')
    return
  }
  
  searchLoading.value = true
  
  try {
    // 模拟搜索API
    const results = await mockSearch(locationSearch.value)
    searchResults.value = results
  } catch (error) {
    console.error('搜索失败:', error)
    ElMessage.error('搜索失败')
  } finally {
    searchLoading.value = false
  }
}

const mockSearch = async (keyword) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve([
        {
          id: 1,
          title: keyword + '附近',
          address: '北京市海淀区中关村大街1号'
        },
        {
          id: 2,
          title: keyword + '商圈',
          address: '北京市朝阳区建国门外大街1号'
        }
      ])
    }, 500)
  })
}

const selectLocation = (location) => {
  form.detailAddress = location.address
}

const confirmLocation = () => {
  showLocationDialog.value = false
}

const handleCloseLocationDialog = () => {
  showLocationDialog.value = false
  searchResults.value = []
  locationSearch.value = ''
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    submitting.value = true
    
    const addressData = {
      ...form,
      fullAddress: getFullAddress()
    }
    
    if (isEdit.value) {
      await addressApi.updateAddress(route.params.id, addressData)
      ElMessage.success('地址更新成功')
    } else {
      await addressApi.createAddress(addressData)
      ElMessage.success('地址添加成功')
    }
    
    router.back()
  } catch (error) {
    if (error !== false) {
      console.error('保存地址失败:', error)
      ElMessage.error('保存地址失败')
    }
  } finally {
    submitting.value = false
  }
}

const getFullAddress = () => {
  const regionText = getRegionText(form.region)
  return regionText + form.detailAddress
}

const getRegionText = (regionCode) => {
  // 根据地区代码获取完整地区名称
  // 这里简化处理，实际应该根据选中的值查找对应的文本
  return '北京市海淀区' // 模拟
}

const handleBack = () => {
  router.back()
}
</script>

<style lang="scss" scoped>
.address-form-page {
  min-height: 100vh;
  background-color: #f5f7fa;
  padding: 20px 0;
}

.container {
  max-width: 600px;
  margin: 0 auto;
  padding: 0 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;

  h1 {
    margin: 0;
    font-size: 20px;
    font-weight: 600;
    color: #333;
  }

  .placeholder {
    width: 32px;
  }
}

.form-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.label-section {
  .preset-labels {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    margin-bottom: 12px;

    .label-tag {
      cursor: pointer;
      transition: all 0.3s ease;

      &:hover {
        transform: translateY(-1px);
      }
    }
  }
}

.location-helper {
  margin-top: 8px;
  text-align: right;
}

.address-tags {
  .el-checkbox-group {
    display: flex;
    flex-wrap: wrap;
    gap: 16px;
  }
}

.form-actions {
  margin-top: 32px;
  text-align: center;

  .el-button {
    min-width: 120px;
  }
}

.location-content {
  .search-section {
    margin-bottom: 16px;
  }

  .map-container {
    margin-bottom: 16px;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    
    #location-map {
      background-color: #f5f7fa;
      display: flex;
      align-items: center;
      justify-content: center;
      color: #909399;
      font-size: 14px;
    }
  }

  .location-results {
    h4 {
      margin: 0 0 12px 0;
      font-size: 14px;
      color: #666;
    }

    .result-item {
      padding: 12px;
      border: 1px solid #e4e7ed;
      border-radius: 4px;
      margin-bottom: 8px;
      cursor: pointer;
      transition: all 0.3s ease;

      &:hover {
        border-color: #409eff;
        background-color: #f0f9ff;
      }

      h5 {
        margin: 0 0 4px 0;
        font-size: 14px;
        font-weight: 500;
        color: #333;
      }

      p {
        margin: 0;
        font-size: 12px;
        color: #666;
      }
    }
  }
}

@media (max-width: 768px) {
  .container {
    padding: 0 10px;
  }

  .page-header {
    h1 {
      font-size: 18px;
    }
  }

  :deep(.el-form-item__label) {
    width: 80px !important;
  }

  .preset-labels {
    .label-tag {
      font-size: 12px;
      padding: 4px 8px;
    }
  }

  .address-tags {
    .el-checkbox-group {
      flex-direction: column;
      gap: 8px;
    }
  }
}
</style> 